import React, {useEffect, useState} from 'react';
import {Button, Empty, Flex, GetProps, Input, Space, Table, Tag} from 'antd';
import type {TableColumnsType, TableProps} from 'antd';
import {useNavigate} from "react-router";
import {deleteArticleAPI, getArticleListAPI} from "@api/Article";
import {message} from "antd/lib";

import './index.less';

type SearchProps = GetProps<typeof Input.Search>;
const {Search} = Input;

// 定义表格数据类型
interface DataType {
    _id: string
    title: string
    updatedAt: string
    tags: string[]
    likeCount: number
    readCount: number
    collectCount: number
    commentCount: number
    state: boolean
}

interface TableParams {
    page: number;
    pageSize: number;
    sort: {
        _id: number
    },
    filter: {
        title: {
            $regex: string,
            $options: string
        },
        state?: boolean
    }
}

function ArticleManage() {
    
    type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];
    const navigate = useNavigate();
    // 定义文章总数
    const [total, setTotal] = useState(0);
    // 定义表格列表头
    const columns: TableColumnsType<DataType> = [
        {title: '文章名称', dataIndex: 'title'},
        {
            title: '标签', dataIndex: 'tags',
            render: (_, record) => (
                record.tags.map((tag: string) => (
                    <Tag key={tag} color="purple">{tag}</Tag>
                ))
            )
        },
        {
            title: '更新时间', dataIndex: 'updatedAt',
            render: (_, record) => {
                return record.updatedAt.slice(0, 10)
            }
        },
        {title: '点赞数', dataIndex: 'likeCount'},
        {title: '阅读数', dataIndex: 'readCount'},
        {title: '收藏数', dataIndex: 'collectCount'},
        {title: '评论数', dataIndex: 'commentCount'},
        {
            title: '发布状态',
            dataIndex: 'state',
            width: 120,
            render: (_, record) => (
                record.state ? <Tag color="green">
                    已发布
                </Tag> : <Tag color="red">
                    草稿箱
                </Tag>
            ),
            filters: [
                {text: '已发布', value: true},
                {text: '草稿箱', value: false}
            ]
            
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 180,
            render: (_, records) => (
                <>
                    <Space>
                        <Button type="primary" onClick={() => editArticle(records)}>编辑</Button>
                        <Button type="primary" className="showArticle">查看</Button>
                        <Button danger className="deleteArticle"
                                onClick={() => {deleteSimpleArticle(records)}}>删除</Button>
                    </Space>
                </>
            
            )
        }
    ];
    // 定义选中行
    const [selectRow, setSelectRow] = useState<boolean>(true);
    // 定义搜索值
    const [searchValue, setSearchValue] = useState('')
    // 定义 loading
    const [loading, setLoading] = useState(false)
    // 定义分页
    const [pageOptions, setPageOptions] = useState<TableParams>({
        page: 1,
        pageSize: 7,
        sort: {
            _id: 1
        },
        filter: {
            title: {
                $regex: searchValue,
                $options: 'i'
            }
        }
    });
    // 定义表格数据
    const [dataSource, setDataSource] = useState<DataType[]>([]);
    // 定义选中行的 key
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    useEffect(() => {
        axiosArticleList();
    }, [pageOptions.page, pageOptions.filter.title, pageOptions.filter.state])
    
    
    // 渲染表格数据
    const axiosArticleList = async () => {
        try {
            const res = await getArticleListAPI(pageOptions);
            setLoading(false)
            setTotal(res.data.data[0].total);
            setDataSource(res.data.data[1]);
        } catch (error) {
            console.error("Error fetching article list:", error);
        }
    };
    // 编辑文章
    const editArticle = (row: any) => {
        // 跳转到编辑文章页面，并传递文章 id 作为参数
        navigate(`/mkbk/article/edit/${row._id}`);
    }
    // 删除单个文章
    const deleteSimpleArticle = async (row: any) => {
        deleteArticleAPI(row._id).then((res) => {
            // 更新页码
            axiosArticleList()
            message.success(res.data.message)
        })
    }
    // 删除多个文章
    const deleteMoreArticle = async () => {
        setLoading(true)
        deleteArticleAPI(selectedRowKeys).then((res) => {
            // 更新页码
            setPageOptions({
                page: pageOptions.page,
                pageSize: pageOptions.pageSize,
                sort: {
                    _id: 1
                },
                filter: {
                    title: {
                        $regex: searchValue,
                        $options: 'i'
                    }
                }
            })
            axiosArticleList()
            message.success(res.data.message)
            // 清空选择行
            setSelectedRowKeys([])
            setSelectRow(true)
        })
    }
    // 选择行的回调函数
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        setSelectRow(!(newSelectedRowKeys.length > 0))
        setSelectedRowKeys(newSelectedRowKeys);
    };
    // 选择行的配置
    const rowSelection: TableRowSelection<DataType> = {
        selectedRowKeys,
        onChange: onSelectChange
    };
    // 分页
    const changePageOption = (pageSize: number, current: number, state: any) => {
        // 如果 state 为空，说明没有筛选条件
        if (state === null) state = [true, false]
        setLoading(true)
        setSelectedRowKeys([])
        setSelectRow(true)
        pageOptions.page = current as number
        setPageOptions({
            page: current as number,
            pageSize: pageSize as number,
            sort: {
                _id: 1
            },
            filter: {
                title: {
                    $regex: searchValue,
                    $options: 'i'
                },
                state
            }
        })
        axiosArticleList()
    }
    const onSearch: SearchProps['onSearch'] = (value, _e) => {
        setLoading(true)
        setSearchValue(value)
        setPageOptions({
            page: 1,
            pageSize: 7,
            sort: {
                _id: 1
            },
            filter: {
                title: {
                    $regex: value,
                    $options: 'i'
                }
            }
        })
        axiosArticleList()
    }
    
    return (
        <>
            <Flex gap="middle" vertical>
                <Flex align="center" gap="middle">
                    <Button type="primary" onClick={() => {navigate("/mkbk/article/add")}}>
                        添加文章
                    </Button>
                    <Button danger disabled={selectRow} onClick={() => deleteMoreArticle()}>删除所选</Button>
                    <Search placeholder="请输入需要搜索的文章标题" onSearch={onSearch} enterButton
                            style={{width: 300}}/>
                </Flex>
                <Table<DataType> rowSelection={rowSelection} columns={columns} dataSource={dataSource}
                                 rowKey="_id"
                                 loading={loading}
                                 pagination={{
                                     total,
                                     pageSize: pageOptions.pageSize,
                                     showSizeChanger: false,
                                     showTotal: (total) => `共 ${total} 条`
                                 }}
                                 onChange={({pageSize, current}, {state}) => {
                                     changePageOption(pageSize as number, current as number, state)
                                 }}
                                 locale={{emptyText: <Empty description="没有相关数据哦"></Empty>}}
                />
            </Flex>
        </>
    );
}

export default ArticleManage;